Skip to main content
ICT
Lesson A4 - Object Behavior
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

F. Getters/Setters page 8 of 11

  1. When you are first starting to program, some of the most commonly used methods are called Getters and Setters (some like to call them Mutators and Accessors). These methods deal directly with attributes of the object they are associated with.

  1. When we are working with an object, sometimes we will need to know certain pieces of information about the object that only the object can tell us reliably. Recall the DrawSquare class that we worked with earlier. We might remember the length of a side, but if that length has changed for some reason during the life of the object, we might be in for a surprise if we used that value. Here we would want to store the side length in a private instance variable and provide a Getter method along the lines of double getSideLength(). The Getter method’s purpose would be to give us current information about that object. We don’t want to let other objects access the side length directly, because they might alter that data when we don’t want them to. The getSideLength method allows other objects to look at the data in our DrawSquare object and storing the length in a private variable prevents these objects from directly accessing the length.

  2. What happens if we do want to change that side length from outside our class? As it stands right now, that would not be possible. However, we could create a Setter method in the DrawSquare class that would do this for us, void setSideLength(double d). This method’s basic purpose is to change the value of the sides for us, but it could also do a bit more. For instance, what if someone passed setSideLength a value of negative 10? Our square could obviously not exist with a negative side value, so our Setter program should check for validity of the values. Setters can often do calculations for us when necessary, so they are not always simply changing a value and doing nothing else. Often, Setter methods are given a return type of boolean which will return true if the value was valid and false if the value was not. This lets clients know if their value was accepted or not. If the client sends an invalid value to a method, it is usually good for them to know that they tried to use the method incorrectly.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.